import { ref, computed, watch, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import type { WatchStopHandle } from 'vue'
import { useAiTimelineStore } from '../../../stores/aiTimeline'
import type { EditorTab } from '../../../types/editor'
import type { AiTimelineEntry } from '../../../stores/aiTimeline'

/**
 * AI时间线监听器 - 监听文件的AI记录变化，自动切换编辑器模式
 * 
 * 功能：
 * 1. 监听指定文件的AI时间线记录变化
 * 2. 当文件有AI记录时自动切换到diff编辑器
 * 3. 当文件AI记录被清除时自动切换回普通编辑器
 * 4. 支持实时响应AI记录的增删变化
 */
export function useAiTimelineWatcher(tab: EditorTab) {
  const aiTimelineStore = useAiTimelineStore()
  const isWatching = ref(false)
  const hasAiRecords = ref(false)
  const latestEntry = ref<AiTimelineEntry | null>(null)
  // 缓存当前文件的所有条目，用于聚合基线
  const entriesForFile = ref<AiTimelineEntry[]>([])
  // 上次签名（用于判断与当前文件相关的时间线是否发生变化）
  const lastSignature = ref<string>('')
  
  // 计算当前文件是否应该显示diff模式
  const shouldShowDiff = computed(() => {
    return hasAiRecords.value && latestEntry.value
  })
  
  // 计算用于聚合的original基线：取时间线中最早一条包含beforeContent的内容
  function computeAggregatedOriginal(): { original: string, entryCount: number, baselineEntryId?: string } {
    const list = entriesForFile.value || []
    const entryCount = list.length
    if (entryCount === 0) return { original: String(tab.savedContent || ''), entryCount }
    const asc = list.slice().sort((a, b) => a.ts - b.ts)
    const earliestWithBefore = asc.find(e => typeof e.beforeContent === 'string')
    const original = (earliestWithBefore?.beforeContent ?? tab.savedContent ?? '') + ''
    return { original, entryCount, baselineEntryId: earliestWithBefore?.id }
  }
  
  // 便捷方法：当与当前文件相关的AI时间线发生变化时，更新一个强制重渲染的key
  function bumpEditorRerenderKey(reason?: string) {
    try {
      const oldKey = tab.editorRerenderKey
      const salt = Math.random().toString(36).slice(2, 6)
      const newKey = `ai-refresh:${Date.now()}:${salt}`
      tab.editorRerenderKey = newKey
      console.log('[AI时间线监听器] 编辑器重渲染触发:', {
        原因: reason || '未指定',
        旧Key: oldKey,
        新Key: newKey,
        标签页路径: tab.path,
        时间戳: new Date().toLocaleTimeString()
      })
    } catch (error) {
      console.error('[AI时间线监听器] bumpEditorRerenderKey 执行失败:', error)
    }
  }
  
  // 检查文件的AI记录状态
  async function checkAiRecords() {
    if (!tab.path) {
      hasAiRecords.value = false
      latestEntry.value = null
      entriesForFile.value = []
      return
    }
    
    try {
      const entries = await aiTimelineStore.getEntriesForFile(tab.path)
      const latest = entries.length > 0 ? entries[0] : null
      
      hasAiRecords.value = entries.length > 0
      latestEntry.value = latest
      entriesForFile.value = entries
      
      // 更新tab的AI状态
      if (latest) {
        tab.aiStatus = {
          hasChanges: true,
          latestEntry: latest,
          totalChanges: entries.length,
          kind: latest.kind,
          tool: latest.tool,
          timestamp: latest.ts
        }
      } else {
        tab.aiStatus = null
      }
      
    } catch (error) {
      console.warn('检查AI记录失败:', error)
      hasAiRecords.value = false
      latestEntry.value = null
      entriesForFile.value = []
      tab.aiStatus = null
    }
  }
  
  // 应用编辑器模式切换
  function applyEditorMode() {
    const shouldDiff = shouldShowDiff.value
    
    if (shouldDiff) {
      // 切换到内联diff模式（或保持当前diff模式），并设置聚合基线
      tab.showingDiff = true
      tab.diffSideBySide = false // 强制内联模式
      tab.justSwitchedToDiff = true // 标记刚刚切换到diff模式，用于控制自动选中行为
      
      const { original, entryCount, baselineEntryId } = computeAggregatedOriginal()
      // 使用聚合的original作为对比基线，保证多次AI修改仍对比到最初版本
      tab.systemHistoryDiff = {
        source: 'ai-timeline',
        id: baselineEntryId || (latestEntry.value?.id || 'ai-timeline-aggregated'),
        originalContent: original,
        resourceUri: tab.path || ''
      }
      // 标记聚合diff信息（供其他逻辑参考）
      tab.aggregatedDiff = true
      tab.diffEntryCount = entryCount
      
      console.log(`[AI时间线] 内联diff（聚合基线）: ${tab.path}，条目数: ${entryCount}`)
      
    } else if (!shouldDiff && tab.showingDiff && tab.systemHistoryDiff?.source === 'ai-timeline') {
      // 只有当前diff是由AI时间线触发的才自动切换回普通模式
      tab.showingDiff = false
      tab.diffSideBySide = undefined // 重置diff模式设置
      tab.systemHistoryDiff = null
      tab.diffModels = null
      tab.aggregatedDiff = undefined
      tab.diffEntryCount = undefined
      
      console.log(`[AI时间线] 自动切换到普通模式: ${tab.path}`)
    }
  }
  
  // 监听AI时间线entries的变化
  let entriesWatcher: WatchStopHandle | null = null
  
  // 开始监听
  async function startWatching() {
    if (isWatching.value || !tab.path) return
    
    isWatching.value = true
    
    // 初始检查
    await checkAiRecords()
    applyEditorMode()
    
    // 监听AI时间线store的entries变化（注意：直接传递ref以监听push等变更）
    entriesWatcher = watch(
      aiTimelineStore.entries,
      async (newEntries, oldEntries) => {
        console.log('[AI时间线监听器] 条目变化检测:', {
          文件路径: tab?.path,
          新条目数量: newEntries?.length || 0,
          旧条目数量: oldEntries?.length || 0,
          时间戳: new Date().toLocaleTimeString()
        })

        await checkAiRecords()
        applyEditorMode()

        // AI时间线条目数量发生变化时，从磁盘重新读取文件内容并刷新编辑器
        try {
          if (tab.path) {
            console.log('[AI时间线监听器] 开始从磁盘读取文件内容:', tab.path)
            const { invoke } = await import('@tauri-apps/api/core')
            const diskContent = await invoke<string>('fs_read_text', { path: tab.path })
            const prev = String(tab.content ?? '')
            
            console.log('[AI时间线监听器] 内容比较:', {
              磁盘内容长度: diskContent.length,
              编辑器内容长度: prev.length,
              内容是否相同: prev === diskContent
            })
            
            if (prev !== diskContent) {
              console.log('[AI时间线监听器] 内容不同，更新编辑器内容')
              tab.content = diskContent
              tab.savedContent = diskContent
              // 通知编辑器刷新
              bumpEditorRerenderKey('timeline-changed')
              console.log('[AI时间线监听器] 已触发编辑器重新渲染')
            } else {
              console.log('[AI时间线监听器] 内容相同，无需更新')
            }
          }
        } catch (error) {
          console.error('[AI时间线监听器] 从磁盘重新读取文件失败:', error)
        }
        
        // 仅当与当前文件相关的时间线发生变化时才触发重渲染
        // 使用更细粒度的签名（基于每条记录的id、ts以及内容长度）来感知条目内部更新
        const list = entriesForFile.value || []
        const sig = JSON.stringify(list.map(e => [e.id, e.ts, (e as any).beforeContent?.length ?? -1, (e as any).afterContent?.length ?? -1]))
        if (sig !== lastSignature.value) {
          lastSignature.value = sig
          bumpEditorRerenderKey('timeline-updated')
        }
      },
      { deep: true }
    )
    
    console.log(`[AI时间线] 开始监听文件: ${tab.path}`)
  }
  
  // 停止监听
  function stopWatching() {
    if (!isWatching.value) return
    
    isWatching.value = false
    
    if (entriesWatcher) {
      entriesWatcher()
      entriesWatcher = null
    }
    
    console.log(`[AI时间线] 停止监听文件: ${tab.path}`)
  }
  
  // 手动刷新AI记录状态
  async function refresh() {
    if (!isWatching.value) return
    
    await checkAiRecords()
    applyEditorMode()
  }
  
  const instance = getCurrentInstance()
  if (instance) {
    // 监听tab路径变化
    watch(
      () => tab.path,
      async (newPath, oldPath) => {
        if (newPath !== oldPath) {
          if (oldPath && isWatching.value) {
            stopWatching()
          }
          if (newPath) {
            await startWatching()
          }
        }
      }
    )
  
    // 组件挂载时自动开始监听
    onMounted(() => {
      if (tab.path) {
        startWatching()
      }
    })
    
    // 组件卸载时停止监听
    onBeforeUnmount(() => {
      stopWatching()
    })
  }
  
  return {
    isWatching,
    hasAiRecords,
    latestEntry,
    shouldShowDiff,
    startWatching,
    stopWatching,
    refresh
  }
}

/**
 * 全局AI时间线监听器 - 用于监听所有打开文件的AI记录变化
 * 
 * 使用场景：
 * - 在EditorArea中统一管理所有tab的AI时间线监听
 * - 当AI操作完成后批量更新相关文件的编辑器模式
 */
// 补充类型导入，供全局监听器使用
import type { ActiveTabTracker } from './useActiveTabTracker'
import type { EditorModeController } from './useEditorModeController'

export function useGlobalAiTimelineWatcher() {
  const aiTimelineStore = useAiTimelineStore()
  const watching = ref(false)
  let stop: WatchStopHandle | null = null

  // 与 EditorArea 对接的依赖
  const activeTabTracker = ref<ActiveTabTracker | null>(null)
  const modeController = ref<EditorModeController | null>(null)
  let unbindActiveTabChange: (() => void) | null = null
  // 供 EditorArea 注入的打开文件方法
  const fileOpener = ref<null | ((path: string, opts?: { preview?: boolean; preferDiffMode?: boolean; forcePlainEditor?: boolean }) => Promise<void>)>(null)

  // 跟踪已处理的最新条目，避免初始化时误触发打开
  const lastHandledEntryId = ref<string | null>(null)

  // 初始化：确保时间线已加载，并记录现有最新条目的ID
  async function initialize() {
    try { 
      const list = await aiTimelineStore.loadEntries()
      lastHandledEntryId.value = list.length > 0 ? list[0].id : null
    } catch {}
  }

  function setActiveTabTracker(tracker: ActiveTabTracker) {
    activeTabTracker.value = tracker
    // 绑定活跃标签页变化，实时与时间线同步
    if (unbindActiveTabChange) { try { unbindActiveTabChange() } catch {} unbindActiveTabChange = null }
    if (tracker?.onActiveTabChange) {
      unbindActiveTabChange = tracker.onActiveTabChange(async () => {
        try { await syncWithActiveTab() } catch {}
      })
    }
  }

  function setModeController(controller: EditorModeController) {
    modeController.value = controller
  }

  function setFileOpener(opener: (path: string, opts?: { preview?: boolean; preferDiffMode?: boolean; forcePlainEditor?: boolean }) => Promise<void>) {
    fileOpener.value = opener
  }

  async function hasAiRecord(path: string): Promise<boolean> {
    if (!path) return false
    try {
      const list = await aiTimelineStore.getEntriesForFile(path)
      return list.length > 0
    } catch { return false }
  }

  async function getLatestAiRecord(path: string): Promise<AiTimelineEntry | null> {
    if (!path) return null
    try { return await aiTimelineStore.getLatestEntryForFile(path) } catch { return null }
  }

  async function syncWithActiveTab() {
    const tracker = activeTabTracker.value
    const controller = modeController.value
    if (!tracker || !controller) return

    const tab = tracker.getCurrentActiveTab?.()
    if (!tab || !tab.path) return

    const has = await hasAiRecord(tab.path)
    const latest = has ? await getLatestAiRecord(tab.path) : null
    controller.smartSwitchMode(tab, has, latest, 'ai-timeline')
  }

  function start() {
    if (watching.value) return
    watching.value = true
    // 监听时间线变化，驱动活跃标签页的模式同步与自动跳转
    stop = watch(aiTimelineStore.entries, async (val) => {
      try { 
        // 自动同步活跃标签页模式
        await syncWithActiveTab()
        // 自动跳转到最新变更的文件标签页（若不存在则创建）
        const list = Array.isArray(val) ? val.slice().sort((a, b) => b.ts - a.ts) : []
        const latest = list[0]
        // 如果是首次观察且尚未记录处理过的条目，则仅记录，不触发打开
        if (lastHandledEntryId.value == null) {
          lastHandledEntryId.value = latest?.id ?? null
          return
        }
        if (latest && latest.id !== lastHandledEntryId.value) {
          lastHandledEntryId.value = latest.id
          const open = fileOpener.value
          if (open) {
            try {
              await open(latest.path, { preview: false, preferDiffMode: true })
              // 打开/聚焦后再次同步，确保diff模式立即生效
              await syncWithActiveTab()
            } catch (e) {
              console.warn('[GlobalAiWatcher] open file failed:', e)
            }
          }
        }
      } catch {}
    }, { deep: true })

    // 立即对齐：处理 initialize() 与 start() 之间已经发生但没有进一步变更的条目
    ;(async () => {
      try {
        const list = await aiTimelineStore.loadEntries()
        const latest = list[0]
        if (lastHandledEntryId.value == null) {
          lastHandledEntryId.value = latest?.id ?? null
          return
        }
        if (latest && latest.id !== lastHandledEntryId.value) {
          lastHandledEntryId.value = latest.id
          const open = fileOpener.value
          if (open) {
            try {
              await open(latest.path, { preview: false, preferDiffMode: true })
              await syncWithActiveTab()
            } catch (e) {
              console.warn('[GlobalAiWatcher] immediate open failed:', e)
            }
          }
        }
      } catch {}
    })()
  }

  function stopWatch() {
    if (!watching.value) return
    watching.value = false
    if (stop) { stop(); stop = null }
    if (unbindActiveTabChange) { try { unbindActiveTabChange() } catch {} unbindActiveTabChange = null }
  }

  // 移除自动启动，改由 EditorArea 在完成 initialize 与依赖注入后显式调用 start()
  // onMounted(() => start())
  onBeforeUnmount(() => stopWatch())

  return {
    // 生命周期
    initialize,
    start,
    stop: stopWatch,
    watching,
    // 对接 EditorArea 的 API
    setActiveTabTracker,
    setModeController,
    setFileOpener,
    hasAiRecord,
    getLatestAiRecord,
    syncWithActiveTab,
  }
}